var Q = require('q'),
    _ = require('lodash'),
    BaseFun = require('../../../Base/server/controllers/Function'),
    BaseEnum = require('../../../Base/server/controllers/Enum'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    QCEnum = require('../../../QC/server/controllers/Enum.server.controller'),
    BarcodeEnum = require('../../../Barcode/server/controllers/Enum.server.controller'),

    userController = require('../../../User/server/controllers/users.server.controller'),
    operationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    terminalController = require('../../../CBO/server/controllers/Terminal.server.controller'),
    stationWorkController = require('../../../Initialize/server/controllers/StationWork.server.controller'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller'),
    qcRecordController = require('../../../QC/server/controllers/QCRecord.server.controller'),
    qcStandardController = require('../../../QC/server/controllers/QCStandard.server.controller'),
    badTypeBindController = require('../../../QC/server/controllers/BadTypeBind.server.controller'),
    extendEnumController = require('../../../Common/server/controllers/ExtendEnum.server.controller');

//根据终端UniqueID获取终端、工位、作业集合
exports.getTerminalWorkLocationWorks = function(req, res) {
    //BaseFun.authorizedCheck(req.user, res);
    var parameter = req.body.Parameter;
    var terminalUniqueID = parameter.TerminalUniqueID;

    var returnData = {
        Terminal: null,
        WorkLocation: null,
        Works: []
    };

    //查找终端
    terminalController.findByUniqueID(terminalUniqueID, function(err, terminalRecord) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (terminalRecord == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询终端错误';
                newErr.message = '请检查查询参数！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                returnData.Terminal = terminalRecord;
                stationWorkController.getStationWorksByTerminalID(terminalRecord._id, function(err, stationWorkRecords) {
                    if (err) {
                        res.json({
                            Data: null,
                            Error: err
                        });
                    } else {
                        if (stationWorkRecords.length > 0) {
                            returnData.WorkLocation = stationWorkRecords[0].WorkLocation;
                        }
                        for (var i = 0; i < stationWorkRecords.length; i++) {
                            returnData.Works.push(stationWorkRecords[i].Work);
                        }
                        res.json({
                            Data: returnData,
                            Error: null
                        });
                    }
                });
            }
        }
    });
};

//根据条码和作业获取默人或物的信息
exports.getFirstQCDefaultInfo = function(req, res) {
    //BaseFun.authorizedCheck(req.user, res);
    var self = this;
    var parameter = req.body.Parameter;
    //var workId = parameter.WorkID; //查询流水信息使用
    var barcode = parameter.Barcode,
        firstConfirm = parameter.firstFlag;

    barcodeMasterController.findBarcodeMaster(barcode, function(err, barcodeMasterRecord) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (barcodeMasterRecord == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '条码扫描失败';
                newErr.message = '该条码没有对应的条码主档！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                if (barcodeMasterRecord.BarcodeType == BarcodeEnum.BarcodeType.ItemMaster.Value) {
                    if (firstConfirm) { //首件确认
                        //根据当前作业和物料查找下一工序
                        // operationController.findByItemMasterAndWork(barcodeMasterRecord.ItemMaster, workId, function (err, operationRecord) {
                        //     if (err) {
                        //         res.json({
                        //             Data: null,
                        //             Error: err
                        //         });
                        //         return;
                        //     }
                        if (!barcodeMasterRecord.Operation) {
                            var newErr = new Error();
                            newErr.leval = 9;
                            newErr.title = '查找当前工序失败';
                            newErr.message = '当前工序不存在！';
                            res.json({
                                Data: null,
                                Error: newErr
                            });
                            return;
                        }
                        operationController.findNextOperation(barcodeMasterRecord.Operation.Routing, barcodeMasterRecord.Operation.Sequence).then(function(nextOperation) {
                            var newErr;
                            if (barcodeMasterRecord.QCStatus === QCEnum.QCStatus.Scrap.Value) {
                                newErr = new Error();
                                newErr.leval = 9;
                                newErr.title = '报废扫描';
                                newErr.message = '该单品已报废';
                                res.json({
                                    Data: null,
                                    Error: newErr
                                });
                                return;
                            } else if (barcodeMasterRecord.QCReworkOperation) {
                                if (nextOperation.Sequence > barcodeMasterRecord.QCReworkOperation.Sequence) {
                                    newErr = new Error();
                                    newErr.leval = 9;
                                    newErr.title = '返工异常扫描';
                                    newErr.message = '返工异常扫描，请到返工工序进行扫描';
                                    res.json({
                                        Data: null,
                                        Error: newErr
                                    });
                                    return;
                                }
                            }
                            self.findFirstQCInfo(barcodeMasterRecord, nextOperation.Work._id, function(err, data) {
                                if (err) {
                                    res.json({
                                        Data: null,
                                        Error: err
                                    });
                                    return;
                                }
                                res.json({
                                    Data: { barcodeData: data, workId: nextOperation.Work },
                                    Error: null
                                });
                            });
                        });
                    } else { //首件检验
                        var newErr;
                        if (barcodeMasterRecord.QCStatus === QCEnum.QCStatus.Scrap.Value) {
                            newErr = new Error();
                            newErr.leval = 9;
                            newErr.title = '报废扫描';
                            newErr.message = '该单品已报废';
                            res.json({
                                Data: null,
                                Error: newErr
                            });
                            return;
                        } else if (barcodeMasterRecord.QCReworkOperation) {
                            if (barcodeMasterRecord.Operation.Sequence > barcodeMasterRecord.QCReworkOperation.Sequence) {
                                newErr = new Error();
                                newErr.leval = 9;
                                newErr.title = '返工异常扫描';
                                newErr.message = '返工异常扫描，请到返工工序进行扫描';
                                res.json({
                                    Data: null,
                                    Error: newErr
                                });
                                return;
                            }
                        }
                        self.findFirstQCInfo(barcodeMasterRecord, barcodeMasterRecord.Work._id, function(err, data) {
                            if (err) {
                                res.json({
                                    Data: null,
                                    Error: err
                                });
                                return;
                            }
                            res.json({
                                Data: { barcodeData: data, workId: barcodeMasterRecord.Work },
                                Error: null
                            });
                        });
                    }
                } else if (barcodeMasterRecord.BarcodeType == BarcodeEnum.BarcodeType.Person.Value) {
                    userController.getUserAndRolesInfo(barcodeMasterRecord.EntityID, function(err, userRecord) {
                        if (err) {
                            res.json({
                                Data: null,
                                Error: err
                            });
                        } else {
                            if (userRecord == null) {
                                var newErr = new Error();
                                newErr.leval = 9;
                                newErr.title = '查找员工档失败';
                                newErr.message = '该条码没有对应的员工信息！';
                                res.json({
                                    Data: null,
                                    Error: newErr
                                });
                            } else {
                                delete userRecord._doc.Password;
                                delete userRecord._doc.Image;
                                delete userRecord._doc.Salt;
                                delete userRecord._doc.ResetPasswordToken;
                                delete userRecord._doc.ResetPasswordExpires;
                                res.json({
                                    Data: { User: userRecord },
                                    Error: null
                                });
                            }
                        }
                    });
                } else {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '条码扫描失败';
                    newErr.message = '该条码对应的不是员工或者物料！';
                    res.json({
                        Data: null,
                        Error: err
                    });
                }
            }
        }
    });
};

//提交首件质检信息
exports.setFirstQCInfo = function(req, res) {
    var parameter = req.body.Parameter;
    if (parameter == null || parameter == undefined) {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '参数传入错误';
        newErr.message = 'Parameter值没有';
        res.json({
            Data: null,
            Error: newErr
        });
    }

    var user = parameter.User,
        terminal = parameter.Terminal,
        workLocation = parameter.WorkLocation,
        work = parameter.Work,
        barcodeMaster = parameter.BarcodeMaster,
        bizRecord = parameter.BizRecord,
        qcRecords = parameter.QCRecords;

    //修改条码主档
    var barcodeMasterData = {
        _id: barcodeMaster._id,
        RowStatus: BaseEnum.RowStatus.Modify.Value,
        ModifyBy: user._id,
        SysVersion: barcodeMaster.SysVersion,
        BizRecord: null,
        Operation: null,
        OperationName: null,
        Work: work._id,
        WorkName: work.Name,
        WorkLocation: workLocation._id,
        WorkLocationName: workLocation.Name,
        Terminal: terminal._id,
        TerminalName: terminal.Name,
        QCType: QCEnum.QCType.FirstQuality.Value,
        Users: [user._id]
    };

    //根据物料和作业查找工序
    operationController.findByItemMasterAndWork(barcodeMaster.ItemMaster._id, work._id,
        function(err, operationRecord) {
            if (err) {
                res.json({
                    Data: null,
                    Error: err
                });
            } else {
                if (operationRecord == null) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '查询工序失败';
                    newErr.message = '该物料没有找到对应作业的工序！';
                    res.json({
                        Data: null,
                        Error: newErr
                    });
                } else {
                    barcodeMasterData.Operation = operationRecord._id;
                    barcodeMasterData.OperationName = operationRecord.Name;

                    //创建条码流水数据
                    var bizRecordData = {
                        BarcodeMaster: barcodeMaster._id,
                        Terminal: terminal._id,
                        TerminalName: terminal.Name,
                        Operation: operationRecord._id,
                        OperationName: operationRecord.Name,
                        Work: work._id,
                        WorkName: work.Name,
                        WorkLocation: workLocation._id,
                        WorkLocationName: workLocation.Name,
                        BusinessStatus: null,
                        QCType: QCEnum.QCType.FirstQuality.Value,
                        Remark: bizRecord.Remark
                    };
                    if (user.IsQC) {
                        bizRecordData.QCUser = user._id;
                        bizRecordData.QCDateTime = new Date();
                        bizRecordData.BusinessStatus = BarcodeEnum.BusinessStatus.Complete.Value;
                    } else {
                        bizRecordData.Users = [user._id];
                        bizRecordData.CollectDateTime = new Date();
                        bizRecordData.BusinessStatus = BarcodeEnum.BusinessStatus.Start.Value;
                    }

                    if (bizRecord._id == null || bizRecord._id == undefined) {
                        bizRecordData.RowStatus = BaseEnum.RowStatus.Insert.Value;
                        bizRecordData._id = BaseFun.getObjectId();
                        bizRecordData.CreatedBy = user._id;
                    } else {
                        barcodeMasterData.BizRecord = bizRecord._id;
                        bizRecordData._id = bizRecord._id;
                        bizRecordData.SysVersion = bizRecord.SysVersion;
                        bizRecordData.RowStatus = BaseEnum.RowStatus.Modify.Value;
                        bizRecordData.ModifyBy = user._id;
                    }

                    //创建品质记录
                    var qcRecordDatas = [];
                    var isQualified = true;
                    for (var i = 0; i < qcRecords.length; i++) {
                        var qcRecordData = {
                            BizRecord: null,
                            QCNorm: qcRecords[i].QCNorm._id,
                            QCStandard: qcRecords[i].QCStandard._id,
                            NormValue: qcRecords[i].NormValue,
                            IsQualified: qcRecords[i].IsQualified
                        };
                        if (bizRecord._id == null || bizRecord._id == undefined) {
                            qcRecordData.RowStatus = BaseEnum.RowStatus.Insert.Value;
                            qcRecordData.CreatedBy = user._id;
                        } else {
                            qcRecordData._id = qcRecords[i]._id;
                            qcRecordData.RowStatus = BaseEnum.RowStatus.Modify.Value;
                            qcRecordData.SysVersion = qcRecords[i].SysVersion;
                            qcRecordData.ModifyBy = user._id;
                            qcRecordData.BizRecord = bizRecord._id;
                        }
                        if (qcRecords[i].IsQualified == false ||
                            qcRecords[i].IsQualified == null ||
                            qcRecords[i].IsQualified == undefined) {
                            isQualified = false;
                        }
                        qcRecordDatas.push(qcRecordData);
                    }
                    if (user.IsQC) {
                        if (isQualified) {
                            bizRecordData.QCStatus = QCEnum.QCStatus.Qualified.Value;
                            barcodeMasterData.QCStatus = QCEnum.QCStatus.Qualified.Value;
                            for (var j = 0; j < qcRecords.length; j++) {
                                if (!qcRecords[j].QCStandard.ValueUpperLimit || !qcRecords[j].QCStandard.ValueLowerLimit || qcRecords[j].NormValue > qcRecords[j].QCStandard.ValueUpperLimit ||
                                    qcRecords[j].NormValue < qcRecords[j].QCStandard.ValueLowerLimit) {
                                    bizRecordData.QCStatus = QCEnum.QCStatus.Special.Value;
                                    barcodeMasterData.QCStatus = QCEnum.QCStatus.Special.Value;
                                    break;
                                }
                            }
                        } else {
                            barcodeMasterData.QCStatus = QCEnum.QCStatus.NotQualified.Value;
                            bizRecordData.QCStatus = QCEnum.QCStatus.NotQualified.Value;
                        }
                    }

                    if (bizRecordData.RowStatus == BaseEnum.RowStatus.Insert.Value) {
                        // delete bizRecordData.RowStatus;
                        var bindContext = { User: barcodeMaster.Users ? barcodeMaster.Users[0] : null };
                        _.merge(bindContext, {
                            WorkLocation: bizRecordData.WorkLocation,
                            WorkLocationName: bizRecordData.WorkLocationName,
                            Work: bizRecordData.Work,
                            WorkName: bizRecordData.WorkName
                        });
                        barcodeMasterController.streamValidation(barcodeMaster, operationRecord, bindContext)
                            .then(function(processException) {
                                    barcodeMasterData.BizRecord = bizRecordData._id;
                                    for (var i = 0; i < qcRecordDatas.length; i++) {
                                        qcRecordDatas[i].BizRecord = bizRecordData._id;
                                    }
                                    Q.nfcall(Transaction.BatchSaveByTran, [
                                        { EntityName: 'BizRecord', Records: [bizRecordData] },
                                            processException,
                                        { EntityName: 'QCRecord', Records: qcRecordDatas },
                                        { EntityName: 'BarcodeMaster', Records: [barcodeMasterData] }
                                    ]).then(function() {
                                        res.json({
                                            Data: true,
                                            Error: null
                                        });
                                    }, function(err) {
                                        res.json({
                                            Data: null,
                                            Error: err
                                        });
                                    });
                                },
                                function(err) {
                                    res.json({
                                        Data: null,
                                        Error: err
                                    });
                                });
                    } else {
                        Q.nfcall(Transaction.BatchSaveByTran, [
                            { EntityName: 'BarcodeMaster', Records: [barcodeMasterData] },
                            { EntityName: 'BizRecord', Records: [bizRecordData] },
                            { EntityName: 'QCRecord', Records: qcRecordDatas }
                        ]).then(function() {
                            res.json({
                                Data: true,
                                Error: null
                            });
                        }, function(err) {
                            res.json({
                                Data: null,
                                Error: err
                            });
                        });
                    }
                }
            }
        });
};

//根据条码主档记录和作业ID查找首件质检信息
exports.findFirstQCInfo = function(barcodeMaster, workId, completeFun) {
    var returnData = {
        BarcodeMaster: null,
        BizRecord: {
            _id: null,
            User: null,
            CollectDateTime: null,
            QCUser: null,
            QCDateTime: null,
            Remark: null
        },
        QCRecords: []
    };

    returnData.BarcodeMaster = {
        _id: barcodeMaster._id,
        Barcode: barcodeMaster.Barcode,
        ItemMasterCode: barcodeMaster.ItemMasterCode,
        ItemMasterName: barcodeMaster.ItemMasterName,
        QCStatus: barcodeMaster.QCStatus,
        DescSeg1: barcodeMaster.DescSeg1,
        DescSeg2: barcodeMaster.DescSeg2,
        MO: null,
        ItemMaster: null,
        Work: null,
        SysVersion:barcodeMaster.SysVersion
    };

    if (barcodeMaster.Work != null) {
        returnData.BarcodeMaster.Work = {
            _id: barcodeMaster.Work._id,
            Name: barcodeMaster.Work.Name
        }
    }
    if (barcodeMaster.MO != null) {
        returnData.BarcodeMaster.MO = {
            _id: barcodeMaster.MO._id, //MO ID
            Code: barcodeMaster.MO.Code, //单号
            LotNumber: barcodeMaster.MO.LotNumber //批次
        };
    }
    if (barcodeMaster.ItemMaster != null) {
        returnData.BarcodeMaster.ItemMaster = {
            _id: barcodeMaster.ItemMaster._id, //料品ID
            Code: barcodeMaster.ItemMaster.Code, //料号
            Name: barcodeMaster.ItemMaster.Name, //品名
            Specification: barcodeMaster.ItemMaster.Specification //规格/型号
        }
    }

    //查找条码流水
    bizRecordController.findByBarcodeMasterAndWork(barcodeMaster._id, workId, function(err, bizRecord) {
        if (err) {
            completeFun(err);
        } else {
            if (bizRecord == null) {
                if (barcodeMaster.ItemMaster) {
                    //查找检验标准
                    queryQCStandards(barcodeMaster.ItemMaster._id, barcodeMaster.ItemMaster.ItemCategory, workId, barcodeMaster.DescSeg3, function(err, standardRecords) {
                        if (err) {
                            completeFun(err);
                        } else {
                            for (var i = 0; i < standardRecords.length; i++) {
                                var enumValues = null;
                                if (standardRecords[i].QCNorm.ExtendEnum != null && standardRecords[i].QCNorm.ExtendEnum != undefined) {
                                    enumValues = standardRecords[i].QCNorm.ExtendEnum.Options;
                                }
                                returnData.QCRecords.push({
                                    _id: null,
                                    QCNorm: {
                                        _id: standardRecords[i].QCNorm._id,
                                        Name: standardRecords[i].QCNorm.Name,
                                        Type: standardRecords[i].QCNorm.Type,
                                        EnumValues: enumValues
                                    },
                                    QCStandard: {
                                        _id: standardRecords[i]._id,
                                        StandardValue: standardRecords[i].StandardValue,
                                        ValueUpperLimit: standardRecords[i].ValueUpperLimit,
                                        ValueLowerLimit: standardRecords[i].ValueLowerLimit
                                    },
                                    NormValue: null,
                                    IsQualified: false
                                });
                            }
                            completeFun(null, returnData);
                        }
                    });
                } else {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '查询工序失败';
                    newErr.message = '该主档没有对应的物料。';
                    completeFun(newErr);
                }

            } else {
                returnData.BizRecord = {
                    _id: bizRecord._id,
                    CollectDateTime: bizRecord.CollectDateTime,
                    QCUser: bizRecord.QCUser,
                    QCDateTime: bizRecord.QCDateTime,
                    SysVersion:bizRecord.SysVersion,
                    Remark: bizRecord.Remark
                };

                if (bizRecord.Users != null && bizRecord.Users.length > 0) {
                    returnData.BizRecord.User = bizRecord.Users[0]
                }

                //查找品质记录
                qcRecordController.findQCRecordByBizRecordID(bizRecord._id, function(err, qcRecords) {
                    if (err) {
                        completeFun(err);
                    } else {
                        var findExendEnumCount = 0;
                        for (var i = 0; i < qcRecords.length; i++) {
                            var enumValues = null;
                            if (qcRecords[i].QCNorm.ExtendEnum != null && qcRecords[i].QCNorm.ExtendEnum != undefined) {
                                enumValues = qcRecords[i].QCNorm.ExtendEnum.Options;
                            }
                            returnData.QCRecords.push({
                                _id: qcRecords[i]._id,
                                QCNorm: {
                                    _id: qcRecords[i].QCNorm._id,
                                    Name: qcRecords[i].QCNorm.Name,
                                    Type: qcRecords[i].QCNorm.Type,
                                    EnumValues: enumValues
                                },
                                QCStandard: {
                                    _id: qcRecords[i].QCStandard._id,
                                    StandardValue: qcRecords[i].QCStandard.StandardValue,
                                    ValueUpperLimit: qcRecords[i].QCStandard.ValueUpperLimit,
                                    ValueLowerLimit: qcRecords[i].QCStandard.ValueLowerLimit
                                },
                                SysVersion:qcRecords[i].SysVersion,
                                NormValue: qcRecords[i].NormValue,
                                IsQualified: qcRecords[i].IsQualified
                            });
                        }
                        completeFun(null, returnData);
                    }
                });
            }
        }
    });
};

// 根据物料和作业获取缺陷类型
exports.getBadType = function(req, res) {
    var parameter = req.body.Parameter,
        itemMasterId = parameter.ItemMasterId,
        itemCategory = parameter.ItemCategory,
        workId = parameter.WorkId,
        isNet = parameter.DescSeg3;
    queryQCStandards(itemMasterId, itemCategory, workId, isNet, function(err, standardRecords) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        var qcNormIds = [];
        for (var i = 0; i < standardRecords.length; i++) {
            qcNormIds.push(standardRecords[i].QCNorm._id);
        }
        badTypeBindController.findBadTypeByQCNormID(qcNormIds, function(err, badTypeRecords) {
            if (err) {
                res.json({
                    Data: null,
                    Error: err
                });
                return;
            }
            var badType = [];
            for (var i = 0; i < badTypeRecords.length; i++) {
                badType.push(badTypeRecords[i].BadType);
            }
            extendEnumController.findEnumOptions('BadType', function(err, result) {
                if (err) {
                    res.json({
                        Data: null,
                        Error: err
                    });
                    return;
                }
                var badTypeName = [],
                    temp = {};
                for (var i = 0; i < badType.length; i++) {
                    if (temp[badType[i]] === true) {
                        continue;
                    }
                    badTypeName.push({
                        Value: badType[i],
                        Name: result[badType[i]]
                    });
                    temp[badType[i]] = true;
                }

                res.json({
                    Data: badTypeName,
                    Error: null
                });
            });
        });
    });
};

exports.findNextOperation = function(req, res) {

};

function queryQCStandards(itemMasterId, itemCategory, workId, isNet, completeFun) {
    var condition = { ItemMaster: itemMasterId, Work: workId };
    if (isNet === '1') {
        condition.DescSeg1 = isNet;
    } else {
        condition.DescSeg1 = { $ne: '1' };
    }
    qcStandardController.findQCStandards(condition, function(err, standardRecords) {
        if (err) {
            completeFun(err);
            return;
        }
        if (standardRecords.length > 0) {
            completeFun(null, standardRecords);
            return;
        }
        var newCondition = { ItemCategory: itemCategory, Work: workId };
        if (isNet === '1') {
            newCondition.DescSeg1 = isNet;
        } else {
            newCondition.DescSeg1 = { $ne: '1' };
        }
        qcStandardController.findQCStandards(newCondition, function(err, records) {
            if (err) {
                completeFun(err);
                return;
            }
            if (records.length === 0) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询检验标准错误';
                newErr.message = '不存在对应的检验标准';
                completeFun(newErr);
                return;
            }
            completeFun(null, records);
        });
    });
};
